<template>
  <div class="blog-comment-container" id="comment-container">
    <MessageArea
      title="评论列表"
      :subTitle="`(${data.total})`"
      :list="data.rows"
      :isListLoading="isLoading"
      @submit="handleSubmit"
    />
  </div>
</template>

<script>
import MessageArea from "@/components/MessageArea";
import fetchData from "@/mixins/fetchData.js";
import { getComments, postComment } from "@/api";

export default {
  name: "BlogComment",
  mixins: [fetchData({ total: 0, rows: [] })],
  components: {
    MessageArea,
  },
  data() {
    return {
      page: 1,
      limit: 10,
    };
  },
  created() {
    this.$bus.$on("mainScroll", this.handleScroll);
  },
  destroyed(){
      this.$bus.$off("mainScroll",this.handleScroll);
  },
  methods: {
    async fetchData() {
      return await getComments(this.$route.params.id, this.page, this.limit);
    },
    async handleSubmit(formData, callback) {
      const resp = await postComment({
        blogId: this.$route.params.id,
        ...formData,
      });

      //将新增的评论，加入评论数据中
      this.data.rows.unshift(resp);
      this.data.total++;

      callback("评论成功");
    },
    //加载下一页
    async fetchMore() {
      this.isLoading = true;
      this.page++;
      const resp = await this.fetchData();
      this.data.total = resp.total;
      this.data.rows = this.data.rows.concat(resp.rows);
      this.isLoading = false;
    },

    handleScroll(mainContainer){

        if(this.isLoading||!mainContainer){
            return;
        }
        const range = 100;
        const top = Math.abs(mainContainer.scrollHeight-(mainContainer.scrollTop+mainContainer.clientHeight));
        if(top<range){
            this.fetchMore();
        }
    }
  },
};
</script>

<style scoped lang="less">
.blog-comment-container {
  margin: 30px 0;
}
</style>